import Taro, { Component } from "@tarojs/taro";
import { View, Text, Button, Image, Video } from "@tarojs/components";
import {
  getShareTaskContent,
  shareReturn,
  readReturn
} from "../../actions/task";
import { getSign } from "../../actions/wechat";
import Verification from "../../components/account/verification";
import { addOrder } from "../../actions/task";
import { AtInput, AtCurtain } from "taro-ui";
import wx from "weixin-js-sdk";
import "./sharecontent.less";

class ShareContent extends Component {
  config = {
    navigationBarTitleText: "任务详情"
  };

  state = {
    status: 1,
    content: "",
    title: "",
    name: "",
    tel: "",
    code: null,
    type: 1,
    guide: false,
    ttype: null,
    video: null,
    showCurtain: false
  };

  componentDidMount() {
    // const ios = window.navigator.userAgent.indexOf("iPhone");
    // if (ios > -1) {
    //   this.iosTrouchFn();
    // }
    const { id, puser } = this.$router.params;
    getShareTaskContent({ id, puser }).then(result => {
      if (result && result.state === "000") {
        const {
          content: htmlcontent,
          name: title,
          img,
          type,
          ttype,
          video
        } = result.data;
        var reg = /\<\/?(br){1}\s*\/?\s*\>/gim;
        const content = htmlcontent.replace(reg, "");
        this.setState(
          {
            content,
            title,
            img,
            type,
            ttype,
            video
          },
          () => {
            this.shareWx(this.state.title, this.state.img);
            if (type === 3) {
              setTimeout(() => {
                readReturn({ id, puser });
              }, 10000);
            }
          }
        );
      }
    });
  }

  iosTrouchFn() {
    let startY = 0;
    const scrollBox = document.querySelector(".content-html-con");

    document.body.addEventListener(
      "touchstart",
      e => {
        startY = e.touches[0].pageY;
      },
      { passive: false }
    );

    document.body.addEventListener(
      "touchmove",
      e => {
        const moveY = e.touches[0].pageY;
        const top = scrollBox.scrollTop;
        const ch = scrollBox.clientHeight;
        const sh = scrollBox.scrollHeight;
        if (!this.isChildTarget(e.target, scrollBox)) {
          e.preventDefault();
        } else if (
          (top === 0 && moveY > startY) ||
          (top + ch === sh && moveY < startY)
        ) {
          e.preventDefault();
        }
      },
      { passive: false }
    );
  }

  isChildTarget(child, parent, justChild = flase) {
    let parentNode;
    if (justChild) {
      parentNode = child.parentNode;
    } else {
      parentNode = child;
    }

    if (child && parent) {
      while (parentNode) {
        if (parent === parentNode) {
          return true;
        }
        parentNode = parentNode.parentNode;
      }
    }
    return false;
  }

  showShareMask() {
    this.setState({
      guide: true
    });
  }

  shareWx(title, img) {
    const that = this;
    const { id, puser, from } = this.$router.params;
    var u = navigator.userAgent;
    let share_link =
      window.location.origin +
      "/pages/index/sharecontent?id=" +
      id +
      "&puser=" +
      puser;
    const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
    // let htmlutl = isAndroid
    //   ? window.location.origin +
    //     window.location.pathname +
    //     window.location.search
    //   : from
    //   ? window.location.href
    //   : window.location.origin + "/";
    let htmlutl = isAndroid
      ? window.location.origin +
        window.location.pathname +
        window.location.search
      : sessionStorage.getItem("realIosShareUrl")
    getSign({ url: htmlutl }).then(result => {
      if (result.state === "000") {
        const { data } = result;
        wx.config({
          debug: false,
          appId: data.appid,
          timestamp: data.timestamp,
          nonceStr: data.noncestr,
          signature: data.sign,
          jsApiList: [
            "hideMenuItems",
            "onMenuShareTimeline",
            "onMenuShareAppMessage"
          ]
        });

        wx.hideMenuItems({
          menuList: [
            "menuItem:favorite",
            "menuItem:share:qq",
            "menuItem:share:QZone",
            "menuItem:share:weiboApp",
            "menuItem:copyUrl"
          ], // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录4
          success: function(res) {
            // alert(res);
          }
        });
        wx.checkJsApi({
          jsApiList: [
            "hideMenuItems",
            "onMenuShareTimeline",
            "onMenuShareAppMessage"
          ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function(res) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          }
        });

        wx.ready(() => {
          wx.onMenuShareAppMessage({
            // 分享标题
            title: title,
            // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            desc: title,
            link: share_link,
            // 分享图标
            imgUrl: img,
            // 用户确认分享后执行的回调函数
            success: function () {
              if (!from) {
                that.setState({
                  guide: false,
                  showCurtain: true
                });
              }
              shareReturn({ id, puser });
            }
          });

          wx.onMenuShareTimeline({
            title: title, // 分享标题
            link: share_link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: img,
            success: function() {
              // 设置成功
              if (!from) {
                that.setState({
                  guide: false,
                  showCurtain: true
                });
              };
              shareReturn({ id, puser });
            }
          });
        });
      }
    });
  }

  addOrder() {
    const { id, puser } = this.$router.params;
    const { name, tel, code } = this.state;

    if (name === "") {
      Taro.showToast({
        title: "请输入您的姓名",
        icon: "none",
        duration: 2000
      });
      return false;
    }

    if (tel === "" || !/^1[34578]\d{9}$/.test(tel)) {
      Taro.showToast({
        title: "请输入有效的手机号",
        icon: "none",
        duration: 2000
      });
      return false;
    }
    if (code === "") {
      Taro.showToast({
        title: "请输入手机验证码",
        icon: "none",
        duration: 2000
      });

      return false;
    }
    this.setState(
      {
        name: null,
        tel: null,
        code: null
      },
      () => {
        addOrder({ id, puser, name, tel, code }).then(result => {
          if (result && result.state === "000") {
            Taro.showToast({
              title: result.msg,
              icon: "none",
              duration: 3000
            });
          }
        });
      }
    );
  }

  render() {
    const { status, title, content, type, ttype, img, video } = this.state;
    const { id, from } = this.$router.params;
    return (
      <View className="content-body" id="shareContent">
        <View className="content-head">
          {!from && (
            <View className="content-back-page">
              <Image
                className="back-page"
                onClick={() => {
                  const pathUrl =
                    ttype === 4
                      ? "/pages/index/index"
                      : "/pages/index/task?id=" + id + "&type=" + ttype;
                  Taro.redirectTo({
                    url: pathUrl
                  });
                }}
                src={require("../../assets/img/back.png")}
              />
            </View>
          )}
          <Text className="content-title">{title}</Text>
        </View>
        <View className="content-html-con">
          <View className="content-html">
            {/* <iframe src="https://q.eqxiu.com/s/m6tCH6mg" style="width:100%;height:100vh;" frameborder="0"></iframe> */}
            {type === 1 ? (
              <View dangerouslySetInnerHTML={{ __html: content }} />
            ) : (
              [
                <View dangerouslySetInnerHTML={{ __html: content }} />,
                <Video
                  style="width:100%;height:auto;max-width:100%;display:block;"
                  src={video}
                  controls={true}
                  autoplay={false}
                  poster={img}
                  initialTime="0"
                  id="video"
                  loop={false}
                  muted={false}
                />
              ]
            )}
          </View>
          {ttype < 4 && from ? (
            [
              <View className="form-container">
                <View className="input-con">
                  <AtInput
                    name="name"
                    title="姓名"
                    type="text"
                    value={this.state.name}
                    placeholder="请输入您的姓名"
                    onBlur={() => {
                      setTimeout(window.scrollTo(0, 0), 200);
                    }}
                    onChange={value => {
                      this.setState({
                        name: value
                      });
                    }}
                  />
                  <AtInput
                    name="tel"
                    title="手机号 "
                    type="text"
                    placeholder="请输入您的手机号"
                    value={this.state.tel}
                    onBlur={() => {
                      setTimeout(window.scrollTo(0, 0), 200);
                    }}
                    onChange={value => {
                      this.setState({
                        tel: value
                      });
                    }}

                  />
                  <AtInput
                    clear
                    title="验证码"
                    type="text"
                    maxLength="4"
                    placeholder="请输入验证码"
                    value={this.state.code}
                    border={false}
                    onChange={value => {
                      this.setState({
                        code: value
                      });
                    }}
                    onBlur={() => {
                      setTimeout(window.scrollTo(0, 0), 200);
                    }}
                  >
                    <Verification
                      ref="verifica"
                      status={status}
                      parent={this}
                    />
                  </AtInput>
                </View>

                <Button
                  style="margin:30px 0;background-color:#4FB4FC;border:none;width:80%"
                  type="primary"
                  onClick={this.addOrder.bind(this)}
                >
                  我要瓜分豪礼
                </Button>
              </View>
            ]
          ) : (
            <View className="form-container" />
          )}
        </View>
        {!from && (
          <View
            className="how-to-share"
            onClick={this.showShareMask.bind(this)}
          >
            快来分享任务赚取佣金
          </View>
        )}

        {this.state.guide && (
          <View
            className="share-mask"
            onClick={() => {
              this.setState({
                guide: false
              });
            }}
          >
            <Image
              className="share-img"
              src={require("../../assets/img/share-icon.png")}
            />
          </View>
        )}
        {(!from &&this.state.showCurtain) && (
          <View
            className="share-mask"
            onClick={() => {
              this.setState({
                showCurtain: false
              });
            }}
          >
            <Image
              className="success-img"
              style="width:100%;height:auto"
              src={require("../../assets/img/curtain.png")}
            />
          </View>
        )}
      </View>
    );
  }
}
export default ShareContent;
